<template>
  <div style="display: flex; margin-bottom: 6px">
    <el-button class="btn" @click="polyEditorStart" style="margin-bottom: 5px">开始编辑</el-button>
    <el-button class="btn" @click="createPolygon" style="margin-bottom: 5px">新建围栏</el-button>
    <el-button class="btn" @click="handleKeep" style="margin-bottom: 5px">保存</el-button>
    <el-button class="btn" @click="handleRemove" style="margin-bottom: 5px">删除围栏</el-button>
    <el-button class="btn" @click="polyEditorEnd">结束编辑</el-button>
    <el-input style="width: 220px; height: 32px; margin-left: 6px" placeholder="搜索地点" v-model="searchQuery1" />
  </div>
  <!-- <div :class="['ul_box', searchResults1.length ? 'ul_h' : '']">
    <template v-for="(item, index) in searchResults1" :key="index">
      <div v-if="isFromAddress" class="item" @click="onLocationSelect(index, 1)">
        {{ item.name }}
      </div>
    </template>
  </div> -->
  <div id="maps"></div>
</template>
<script setup>
import { onMounted, onUnmounted, ref, defineExpose, defineProps, watchEffect, watch } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";

let map = null;
let polygon = null; //当前标记的点实例
let polyEditor = null; //编辑器
let PolygonoArr = ref(null); //标记的数组点
let searchQuery1 = ref(); //上车地址查询
let placeSearch = ref(null); //地图搜索插件
let preventWatch = ref(false); //控制是否触发搜索
let isFromAddress = ref(false); //控制是否触发搜索

const props = defineProps({
  rowMapLocData: { type: Array, default: () => [] },
});
watch(searchQuery1, (newVal) => {
  if (!preventWatch.value) {
    if (newVal) {
      onSearch(searchQuery1.value, 1);
    } else {
      searchResults1.value = [];
    }
  }
});
let onSearch = (keyword, type) => {
  if (!placeSearch.value) {
    return;
  }
  placeSearch.value.search(keyword, (status, result) => {
    console.log(status);
    console.log(result);
    console.log(keyword);
    if (status === "complete" && result.info === "OK") {
      if (type == 1) {
        searchResults1.value = result.poiList.pois;
        isFromAddress.value = true;
      } else {
        searchResults2.value = result.poiList.pois;
        isToAddress.value = true;
      }
      // 假设this.map是你的AMap地图实例
      if (result.poiList.pois.length > 0) {
        const firstPoi = result.poiList.pois[0];
        map.setZoomAndCenter(17, [firstPoi.location.lng, firstPoi.location.lat]); // 街道级别的缩放是17
      }
    }
  });
};

//点击搜索到每一项触发
// const onLocationSelect = (index, type) => {
//   let selectedPoi;
//   if (type == 1) {
//     selectedPoi = searchResults1.value[index];
//   }
//   if (!selectedPoi) return;
//   preventWatch.value = true; // 不触发watch
//   if (type == 1) {
//     searchQuery1.value = selectedPoi.name;
//     searchResults1.value = [];
//     isFromAddress.value = false;
//   }
//   const position = [selectedPoi.location.lng, selectedPoi.location.lat];
//   placeMarker(position);
//   setTimeout(() => {
//     preventWatch.value = false;
//   }, 200); // 控制可以搜索
// };

//检测有数据就赋值
watchEffect(() => {
  console.log("props.rowMapLocData", props.rowMapLocData);
  // if (props.rowMapLocData.length > 0) {
  PolygonoArr.value = props.rowMapLocData;
  initMap();
  // }
});
function polyEditorStart() {
  polyEditor.open();
}
//新建围栏
function createPolygon() {
  polyEditor.close();
  polyEditor.setTarget();
  polyEditor.open();
}
//保存
function handleKeep() {
  //获取当前编辑对象
  let a = polyEditor.getTarget();
  //结束编辑
  polyEditor.close();
  PolygonoArr.value = a._opts.path;
  initMap();
}
function handleRemove() {
  map.remove(polygon); //可删除某
  PolygonoArr.value = [];
  initMap();
}
function polyEditorEnd() {
  polyEditor.close();
}

//获取围栏编辑后的经纬度 给父组件出发
async function getLoction() {
  return PolygonoArr.value;
}

onMounted(() => {
  initMap();
});

//初始化查询地图
function initMap() {
  window._AMapSecurityConfig = {
    securityJsCode: "d9bb6af5397ae140433f57fc892608ad", // 申请key对应的秘钥 -> 注意了，如果不搭配密钥使用，搜索将没有结果
  };
  AMapLoader.load({
    key: "24e9f8aa4e598a8db6b458f78d29f93f", // 申请好的Web端开发者Key，首次调用 load 时必填
    // key: "3e4c1f76807c5beae8aef6c4a6af69dd", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.Scale", "AMap.Polygon", "AMap.PolyEditor", "AMap.PolygonEditor", "AMap.PlaceSearch"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })
    .then((AMap) => {
      map = new AMap.Map("maps", {
        // 设置地图容器id
        viewMode: "3D", // 是否为3D地图模式
        zoom: 11, // 初始化地图级别
        center: PolygonoArr.value ? PolygonoArr.value[0] : [116.397428, 39.90923], // 初始化地图中心点位置
      });
      placeSearch.value = new AMap.PlaceSearch({
        map: map,
      });
      //控制地图双击是否放大
      map.setStatus({ doubleClickZoom: false });
      polygon = new AMap.Polygon({
        path: PolygonoArr.value,
        strokeColor: "#1b38d3",
        strokeOpacity: 1,
        strokeWeight: 3,
        fillColor: "#1b38d3",
        fillOpacity: 0,
        zIndex: 50,
        // draggable: true,
        bubble: true,
      });
      // 创建多边形编辑器对象
      polyEditor = new AMap.PolygonEditor(map, polygon);
      polygon.on("dblclick", () => {
        polyEditor.open();
      });

      polygon.on("click", () => {
        polyEditor.close();
      });

      map.add([polygon]);
    })
    .catch((e) => {
      console.log(e);
    });
}

defineExpose({
  getLoction,
});

onUnmounted(() => {
  map?.destroy();
});
</script>

<style lang="scss" scoped>
.ul_h {
  height: 140px;
}
.ul_box {
  background: #fefefe;
  overflow: auto;
  .item {
    margin: 0 0 6px 10px;
  }
  .item:hover {
    background: #f5f5f5;
  }
}
#maps {
  width: 100%;
  height: 400px;
}
</style>
